<?php

namespace App\Http\Controllers;

use App\Http\Resources\CatResource;
use App\Models\Cat;
use App\Http\Requests\StoreCatRequest;
use App\Http\Requests\UpdateCatRequest;
use Illuminate\Http\Request;

class CatController extends Controller
{
    public function __construct() {
         $this->middleware(['auth:sanctum'])->except(['index','show']);
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $cats = CatResource::collection(Cat::orderBy('sort')->get());
        return $this->success(data:$cats);
    }


    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreCatRequest $request,Cat $cat)
    {
        $this->authorize('create',$cat);
        $cat->fill($request->input())->save();
        return $this->success('帖子大类新增成功',new CatResource($cat->refresh()));
    }

    /**
     * Display the specified resource.
     */
    public function show(Cat $cat)
    {
        return $this->success(data:new CatResource($cat));
    }


    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateCatRequest $request, Cat $cat)
    {
        $this->authorize('update',$cat);
        $cat->fill($request->input())->save();
        return $this->success('帖子大类修改成功',new CatResource($cat));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Cat $cat)
    {
        $this->authorize('delete',$cat);
        $cat->delete();
        return $this->success('帖子大类删除成功');
    }

    public function changeSort(Request $request){
        $this->authorize('sort',Cat::class);
        collect($request->cat)->map(function($value,$key){
            $cat = Cat::find($value);
            $cat->sort = $key;
            $cat->save();
        });
        return $this->success('排序成功');
    }
}
